package Session;

import Authorization.User;
import IO.Parser;
import Questions.Question;

import java.io.*;

/**
 * Created with IntelliJ IDEA.
 * User: Инесса
 * Date: 30.10.13
 * Time: 0:58
 * To change this template use File | Settings | File Templates.
 */
public class SessionHelper {

    private final static String PATH = "Session.txt";
    private final static String DELIMITER = "/";
    private static final String INDEX_DELIMITER =",";

    /**
     * Сохраняет сессию в файл
     * @param user пользователь
     * @param session его сессия
     * @throws IOException
     */
    public void save(User user, TestSession session) throws IOException {
        FileWriter writer = new FileWriter(PATH, true);
        StringBuilder builder = new StringBuilder(100);

        builder.append(user.getLogin()); // 0 - element
        builder.append(DELIMITER);
        for(int idexes: session.getLevelArray()){
            builder.append(idexes);
            builder.append(INDEX_DELIMITER);
        }                                              //1 - element
        builder.append(DELIMITER);
        builder.append(session.getCurrentLevel());                  // 2 - element
        builder.append(DELIMITER);
        builder.append(session.getSessionPoints());     //4 - element
        builder.append(DELIMITER);
        for(String oneAnswer: session.getAnswers()){
            builder.append(oneAnswer);
            builder.append(INDEX_DELIMITER);
        }                                          // 5 - element
        builder.append(DELIMITER);
        builder.append("\r\n");

        writer.append(builder);
        writer.close();
    }

    /**
     * Метод возвращает предыдущую сессию пользователя
     * @param user  юзер
     * @return сессия из файла
     * @throws IOException
     */
    public TestSession get(User user, Question[] questions) throws IOException {
        BufferedReader file = new BufferedReader(new FileReader(PATH));
        String line;
        String[] sessionLineElements = null;

        while ((line = file.readLine()) != null) {
            sessionLineElements = line.split(DELIMITER);
            if (user.getLogin().equals(sessionLineElements[0])) {
                break;
            }
        }
        file.close();
        int[] levelArray;
        if (sessionLineElements != null) {
            levelArray = Parser.parseInts(sessionLineElements[1].split(","));

        int lastLevel = Integer.parseInt(sessionLineElements[2]);
        int savedPoints = Integer.parseInt(sessionLineElements[3]);
        String[] savedAnswers = sessionLineElements[4].split(",");
        return new TestSession(questions,levelArray,lastLevel,savedPoints,savedAnswers);
        }
        else return new TestSession(questions);
    }

    /**
     * Удаляем старую сессию насколько я понял
     * @param user пользователь
     * @throws IOException
     */
    public void remove(User user) throws IOException {
        File file = new File(PATH);
        BufferedReader reader = new BufferedReader(new FileReader(file));
        StringBuilder builder = new StringBuilder(100);
        String line;
        boolean removed = false;

        while ((line = reader.readLine()) != null) {
            String[] split = line.split(DELIMITER);
            if (!user.getLogin().equals(split[0])) {
                builder.append(line);
                builder.append("\r\n");
            } else {
                removed = true;
            }
        }

        reader.close();

        if (removed) {
            BufferedWriter writer = new BufferedWriter(new FileWriter(file, false));
            writer.write(builder.toString());
            writer.close();
        }
    }

    /**
     * Проверка на то есть ли незаконченая сессия у пользователя
     * @param user авториз пользователь
     * @return есть ли сессия
     * @throws IOException
     */
    public boolean hasSession(User user) throws IOException {
        BufferedReader file = new BufferedReader(new FileReader(PATH));
        String line;

        while ((line = file.readLine()) != null) {
            String[] split = line.split(DELIMITER);
            if (split[0].equals(user.getLogin())) {
                return true;
            }
        }

        file.close();

        return false;
    }
}
